package org.nokatag.system;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * Hibernate连接类
 * @author rebin
 *
 */
public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	@SuppressWarnings("rawtypes")
	public static final ThreadLocal session = new ThreadLocal();

	public HibernateUtil() {
	}

	public static Session currentSession() throws HibernateException {
		Session s = (Session) session.get();
		//-----------------------------------------------------------
		try{
			if(s.connection().isClosed()){
				try{s.close();}catch(Exception se){BugInfoWrint.Print(se);}
				session.remove();
				s=null;
			}
		}catch(Exception se){
			s=null;
		}
		//-----------------------------------------------------------
		if (s == null || !s.isOpen() || !s.isConnected() ) {
			currentNewSession();
			s = (Session) session.get();
		}
		return s;
	}
	
	@SuppressWarnings("unchecked")
	public static Session currentNewSession(){
		Session s = sessionFactory.openSession();
		s.flush();
		s.clear();
		session.set(s);
		return s;
	}

	@SuppressWarnings("unchecked")
	public static void closeSession() throws HibernateException {
		Session s = (Session) session.get();
		session.set(null);
		if (s != null) {
			s.close();
		}
	}

	public static void closeSession(Session session) {
		try {
			if (session != null) {
				session.close();
			}
		} catch (Exception e) {
			BugInfoWrint.Print(e);
		}
	}

	static {
		try {
			Configuration cfg = new Configuration().configure();   
			sessionFactory = cfg.buildSessionFactory();
		} catch (Throwable  ex) {
			 throw new ExceptionInInitializerError(ex);   
		}
	}
	
	
}